import base64
from datetime import datetime
import requests
from bs4 import BeautifulSoup


class Spark:
    def __init__(self, urls_list, my_logg):
        self.login_can(urls_list, my_logg)
        self.http_get()
        self.login()

    def login_can(self, urls_list, my_logg):
        self.encoded_string = urls_list[3] + ":" + urls_list[4]
        self.url = urls_list[5]
        self.name = urls_list[-1]
        self.my_logg = my_logg

    def login(self):
        try:
            response = requests.get(self.url + '/cluster', headers=self.headers, verify=False)
            bs1 = BeautifulSoup(response.text, 'lxml')
            bs2 = bs1.find_all('table', class_='table table-bordered table-condensed table-striped sortable')[2].tbody
            finished_apps = []
            for tr in bs2.find_all("tr"):
                tds = tr.find_all("td")
                if tds[6].text == "FINISHED":
                    today_zero_str = datetime.now().strftime("%Y/%m/%d 00:00:00")
                    today_zero = datetime.strptime(today_zero_str, "%Y/%m/%d %H:%M:%S")
                    second_time = datetime.strptime(tds[4].text, "%Y/%m/%d %H:%M:%S")
                    if second_time > today_zero:
                        app_id = tds[0].a.text
                        finished_apps.append(app_id)
            self.my_logg.info(f"{self.name}大数据平台数量为：%d", len(finished_apps))
            today_zero_str = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
        except:
            self.my_logg.info(f"{self.name}大数据平台vone未连接，请连接")
            today_zero_str = datetime.now().strftime("%Y/%m/%d %H:%M:%S")

    def http_get(self):
        self.headers = {
            'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Authorization': f'Basic {base64.b64encode(self.encoded_string.encode("utf-8")).decode("utf-8")}',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Pragma': 'no-cache',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
            'Referer': self.url + '/cluster',
        }
